<template>
  <div class="auto-release-management bg-background text-foreground p-4">
    <h1 class="mb-6 text-2xl font-bold">自动放行管理</h1>

    <!-- <div class="tabs bg-card mb-6 inline-flex rounded-lg p-1">
      <button v-for="tab in ['personnel', 'vehicle']" :key="tab" @click="btntab(tab)" :class="[
        'rounded-md px-4 py-2 font-medium transition-colors duration-200',
        activeTab === tab
          ? 'bg-primary text-primary-foreground'
          : 'text-muted-foreground hover:bg-muted',
      ]">
        {{ tab === 'personnel' ? '人员' : '车辆' }}
      </button>
    </div> -->
    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="人员" name="人员">
        <div class="search-form bg-card text-card-foreground mb-6 rounded-lg p-6 shadow-sm">
          <QueryForm :model="personnelSearch" :formItems="formItems" @search="searchdata"
            @reset="resetPersonnelSearch" />
        </div>

        <div class="action-buttons mb-6 flex items-center justify-between">
          <div class="space-x-2">
            <!-- <button @click="addPersonnel" class="btn btn-primary">新增</button>
             -->
            <!-- <el-button type="primary" @click="addPersonnel" style="width: 75px; height: 30px;">新增</el-button>
             -->
            <el-button @click="exportPersonnel" style="width: 75px; height: 30px;">导出</el-button>
          </div>
          <!-- <div class="space-x-2">
            <button @click="importPersonnel" class="btn btn-outline">导入</button>
            <button @click="exportPersonnel" class="btn btn-outline">导出</button>
          </div> -->
        </div>

        <div class="bg-card overflow-hidden rounded-lg shadow-sm">

          <el-table ref="tableRef" v-loading="loading" :data="displayedVehicleData" style="width: 100%" align="center"
            class="data-table" :header-cell-style="headerCellStyle" empty-text="暂无数据">
            <!-- <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column> -->

            <el-table-column prop="STAFF_CODE" label="人员编码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="STAFF_NAME" label="人员姓名" header-align="center" align="center"></el-table-column>
            <el-table-column prop="STAFF_TYPE" label="人员类型" header-align="center" align="center"></el-table-column>
            <el-table-column prop="AFFILIATION" label="所属单位" header-align="center" align="center"></el-table-column>
            <el-table-column prop="STAFF_POSITION" label="职位名称" header-align="center" align="center"></el-table-column>
            <el-table-column prop="AUTHORIZATION_TYPE" label="授权类型" header-align="center"
              align="center"></el-table-column>
            <el-table-column prop="REVIEW_TIME" label="授权日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.REVIEW_TIME) }}
              </template>
            </el-table-column>
            <el-table-column prop="END_TIME" label="到期日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.END_TIME) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" header-align="center" align="center">
              <template #default="scope">
                <!-- <el-button type="primary" size="small" @click="editPerson(scope.row)" link>编辑</el-button> -->
                <el-button type="danger" size="small" @click="deletePersonnel(scope.row)" link>解除</el-button>

              </template>
            </el-table-column>
          </el-table>
        </div>


        <!--  -->
        <Pagination v-if="personnelData.length" :tableData="personnelData" @alltabledata="alltabledatass" />




      </el-tab-pane>
      <el-tab-pane label="车辆" name="车辆">
        <div class="search-form bg-card text-card-foreground mb-6 rounded-lg p-6 shadow-sm">

          <QueryForm :model="vehicleSearch" :formItems="vehicleformItems" @search="searchdataCar"
            @reset="resetVehicleSearch" />
        </div>

        <div class="action-buttons mb-6 flex items-center justify-between">
          <div class="space-x-2">

            <el-button @click="exportVehicle" style="width: 75px; height: 30px;">导出</el-button>
          </div>
          <!-- <div class="space-x-2">
            <button @click="importVehicle" class="btn btn-outline">导入</button>
            <button @click="exportVehicle" class="btn btn-outline">导出</button>
          </div> -->
        </div>

        <div class="bg-card overflow-hidden rounded-lg shadow-sm">

          <el-table v-loading="loading" :data="displayedVehicleDataCar" style="width: 100%" align="center"
            class="data-table" :header-cell-style="headerCellStyle" empty-text="暂无数据">
            <!-- <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column> -->

            <el-table-column prop="PLATE_NUMBER" label="车牌号码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
            <el-table-column prop="VEHICLE_TYPE" label="车辆类型" header-align="center" align="center"></el-table-column>
            <el-table-column prop="CarArray" label="授权通行区域" header-align="center" align="center">
              <template #default="scope">
                <div v-for="(item, index) in scope.row.CarArray" :key="index">
                  <el-button size="small">{{ item.staff_name }}</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="STATUS" label="授权类型" header-align="center" align="center"></el-table-column>
            <el-table-column prop="Authorization_Date" label="授权日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.Authorization_Date) }}
              </template>
            </el-table-column>
            <el-table-column prop="EXPIRATION_DATE" label="到期日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.EXPIRATION_DATE) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" header-align="center" align="center">
              <template #default="scope">
                <!-- <el-button type="primary" size="small" @click="editVehicle(scope.row)" link>编辑</el-button> -->
                <el-button type="danger" size="small" @click="deleteVehicle(scope.row)" link>解除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!--  -->
        <Pagination v-if="vehicleData.length" :tableData="vehicleData" @alltabledata="alltabledata" />




      </el-tab-pane>
    </el-tabs>

    <el-dialog class="dialog-from" v-model="isEditDialogOpen" :title="activeName == '人员' ? '自动放行人员管理编辑' : '自动放行车辆管理编辑'"
      width="900" destroy-on-close align-center>
      <div v-if="activeName == '人员'">
        <div class="body-item">
          <div class="box-title">
            <div class="box-color"></div><strong>基本信息</strong>
          </div>
          <div class="box-content">
            <el-form :model="editingRecord" label-width="auto" :rules="rules" ref="formRef">
              <el-row :gutter="80" class="row-item">
                <el-col :span="8">
                  <el-form-item label="人员编码：" label-position="top" prop="STAFF_CODE">
                    <el-input v-model="editingRecord.STAFF_CODE" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="人员姓名：" label-position="top" prop="STAFF_NAME">
                    <el-input v-model="editingRecord.STAFF_NAME" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="人员类型：" label-position="top" prop="STAFF_TYPE">
                    <el-select v-model="editingRecord.STAFF_TYPE" placeholder="请选择" clearable>
                      <el-option label="企业内部人员" value="企业内部人员" />
                      <el-option label="园区工作人员" value="园区工作人员" />
                      <el-option label="承包商人员" value="承包商人员" />
                      <el-option label="临时访客" value="临时访客" />
                      <el-option label="应急救援人员" value="应急救援人员" />
                      <el-option label="上级部门检查人员" value="上级部门检查人员" />
                      <el-option label="驾驶员" value="驾驶员" />
                      <el-option label="押运员" value="押运员" />
                      <el-option label="其他" value="其他" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="80" class="row-item">
                <el-col :span="8">
                  <el-form-item label="性别：" label-position="top" prop="STAFF_GENDER">
                    <el-select v-model="editingRecord.STAFF_GENDER" placeholder="请选择" clearable>
                      <el-option label="男" value="1" />
                      <el-option label="女" value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="所属单位：" label-position="top" prop="AFFILIATION">
                    <el-input type="text" v-model="editingRecord.AFFILIATION" />

                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="职位名称：" label-position="top" prop="STAFF_POSITION">
                    <el-input v-model="editingRecord.STAFF_POSITION" clearable>

                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="80" class="row-item">
                <el-col :span="8">
                  <el-form-item label="授权类型：" label-position="top" prop="AUTHORIZATION_TYPE">
                    <el-select v-model="editingRecord.AUTHORIZATION_TYPE" placeholder="请选择" clearable>
                      <el-option label="长期" value="长期" />
                      <el-option label="临时" value="临时" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="授权日期：" label-position="top" prop="REVIEW_TIME">
                    <input type="datetime-local" id="newPassTime" v-model="editingRecord.REVIEW_TIME"
                      class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="到期日期：" label-position="top" prop="END_TIME">
                    <input type="datetime-local" id="newPassTime" v-model="editingRecord.END_TIME"
                      class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </div>
      <div v-else>
        <div class="body-item">
          <div class="box-title">
            <div class="box-color"></div><strong>基本信息</strong>
          </div>
          <div class="box-content">
            <el-form :model="editingRecord" label-width="auto" :rules="rules" ref="formRef">
              <el-row :gutter="80" class="row-item">
                <el-col :span="8">
                  <el-form-item label="车牌号：" label-position="top" prop="PLATE_NUMBER">
                    <el-input v-model="editingRecord.PLATE_NUMBER" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="司机姓名：" label-position="top" prop="DRIVER_NAME">
                    <el-input v-model="editingRecord.DRIVER_NAME" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="车辆类型：" label-position="top" prop="VEHICLE_TYPE">
                    <el-select v-model="editingRecord.VEHICLE_TYPE" placeholder="请选择" clearable>
                      <el-option label="普货车" value="普货车" />
                      <el-option label="社会车辆" value="社会车辆" />
                      <el-option label="其他" value="其他" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="80" class="row-item">
                <el-col :span="8">
                  <el-form-item label="授权通行区域：" label-position="top" prop="CarArray">
                    <el-select v-model="editingRecord.CarArray" placeholder="请选择" clearable>
                      <el-option label="男" value="1" />
                      <el-option label="女" value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="授权类型：" label-position="top" prop="STATUS">
                    <el-select v-model="editingRecord.STATUS" placeholder="请选择" clearable>
                      <el-option label="长期" value="长期" />
                      <el-option label="临时" value="临时" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="授权日期：" label-position="top" prop="Authorization_Date">
                    <input type="datetime-local" id="newPassTime" v-model="editingRecord.Authorization_Date"
                      class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="80" class="row-item">

                <el-col :span="8">
                  <el-form-item label="到期日期：" label-position="top" prop="EXPIRATION_DATE">
                    <input type="datetime-local" id="newPassTime" v-model="editingRecord.EXPIRATION_DATE"
                      class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitEditPersonnel">确认</el-button>
          <el-button @click="closeEditDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 修改人员新增对话框 -->
  <!-- <Teleport to="body">
    <Transition name="fade" appear>
      <div v-if="isAddDialogOpen && activeTab === 'personnel'">
        <div class="bg-background/80 fixed inset-0 z-50 flex items-center justify-center backdrop-blur-sm">
          <div class="bg-card text-card-foreground w-[800px] rounded-lg p-5 shadow-xl">
            <div class="mb-4 flex items-center justify-between">
              <h3 class="text-lg font-bold">新增人员</h3>
              <button @click="closeAddDialog" class="text-muted-foreground hover:text-foreground">
                <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>

            <div class="grid grid-cols-3 gap-4">
              <div>
                <label class="block text-sm font-medium">人员编码</label>
                <input type="text" v-model="newPersonnel.staffCode" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">人员姓名</label>
                <input type="text" v-model="newPersonnel.staffName" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">人员类型</label>
                <select v-model="newPersonnel.staffType" class="select">
                  人员类型
                  <option value="企业内部人员">企业内部人员</option>
                  <option value="园区工作人员">园区工作人员</option>
                  <option value="承包商人员">承包商人员</option>
                  <option value="临时访客">临时访客</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">性别</label>
                <select v-model="newPersonnel.sexual" class="select">
                  <option value="">请选择性别</option>
                  <option value="1">男</option>
                  <option value="2">女</option>

                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">所属单位</label>

                <select v-model="newPersonnel.affiliation" class="select">
                  <option value="">请选择所属单位</option>
                  <option value="管委会">管委会</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">职位名称</label>
                <select v-model="newPersonnel.staffPosition" class="select">
                  <option value="">请选择职位名称</option>
                  <option value="长期">长期</option>
                  <option value="临时">临时</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权类型</label>
                <select v-model="newPersonnel.authorizationType" class="select">
                  <option value="">请选择授权类型</option>
                  <option value="长期">长期</option>
                  <option value="临时">临时</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权日期</label>
                <input type="datetime-local" v-model="newPersonnel.reviewTime" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">到期日期</label>
                <input type="datetime-local" v-model="newPersonnel.endTime" class="input" />
              </div>
            </div>

            <div class="mt-4 flex justify-end">
              <button @click="submitNewPersonnel" class="btn btn-primary mr-2">
                确定
              </button>
              <button @click="closeAddDialog" class="btn btn-outline">
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport> -->

  <!-- 修改人员编辑对话框 -->
  <!-- <Teleport to="body">
    <Transition name="fade" appear>
      <div v-if="isEditDialogOpen && activeTab === 'personnel'">
        <div class="bg-background/80 fixed inset-0 z-50 flex items-center justify-center backdrop-blur-sm">
          <div class="bg-card text-card-foreground w-[800px] rounded-lg p-5 shadow-xl">
            <div class="mb-4 flex items-center justify-between">
              <h3 class="text-lg font-bold">编辑人员</h3>
              <button @click="closeEditDialog" class="text-muted-foreground hover:text-foreground">
                <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>

            <div class="grid grid-cols-3 gap-4">
              <div>
                <label class="block text-sm font-medium">人员编码</label>
                <input type="text" v-model="editingRecord.staffCode" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">人员姓名</label>
                <input type="text" v-model="editingRecord.staffName" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">人员类型</label>
                <select v-model="editingRecord.staffType" class="select">
                  <option value="企业内部人员">企业内部人员</option>
                  <option value="园区工作人员">园区工作人员</option>
                  <option value="承包商人员">承包商人员</option>
                  <option value="临时访客">临时访客</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">性别</label>
                <select v-model="editingRecord.sexual" class="select">
                  <option value="1">男</option>
                  <option value="2">女</option>

                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">所属单位</label>
                <input type="text" v-model="editingRecord.affiliation" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">职位名称</label>
                <select v-model="editingRecord.staffPosition" class="select">
                  <option value="长期">长期</option>
                  <option value="临时">临时</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权类型</label>

                <select v-model="editingRecord.authorizationType" class="select">
                  <option value="">请选择授权类型</option>
                  <option value="长期">长期</option>
                  <option value="临时">临时</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权日期</label>
                <input type="datetime-local" v-model="editingRecord.reviewTime" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">到期日期</label>
                <input type="datetime-local" v-model="editingRecord.endTime" class="input" />
              </div>
            </div>
            <div class="mt-4 flex justify-end">
              <button @click="submitEditPersonnel" class="btn btn-primary mr-2">
                确定
              </button>
              <button @click="closeEditDialog" class="btn btn-outline">
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport> -->

  <!-- 修改车辆新增对话框 -->
  <!-- <Teleport to="body">
    <Transition name="fade" appear>
      <div v-if="isAddDialogOpen && activeTab === 'vehicle'">
        <div class="bg-background/80 fixed inset-0 z-50 flex items-center justify-center backdrop-blur-sm">
          <div class="bg-card text-card-foreground w-[800px] rounded-lg p-5 shadow-xl">
            <div class="mb-4 flex items-center justify-between">
              <h3 class="text-lg font-bold">新增车辆</h3>
              <button @click="closeAddDialog" class="text-muted-foreground hover:text-foreground">
                <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>
            <div class="grid grid-cols-3 gap-4">
              <div>
                <label class="block text-sm font-medium">车牌号</label>
                <input type="text" v-model="newVehicle.plateNumber" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">驾驶员姓名</label>
                <input type="text" v-model="newVehicle.driverName" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">车辆类型</label>

                <select v-model="newVehicle.vehicleType" class="select">
                  <option value="">请选择授权区域</option>
                  <option value="普货车">普货车</option>
                  <option value="社会车辆">社会车辆</option>
                  <option value="其他">其他</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权区域</label>
                <select v-model="newVehicle.passArea" class="select">
                  <option value="">请选择授权区域</option>
                  <option value="综合服务区">综合服务区</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权类型</label>
                <select v-model="newVehicle.authorizationType" class="select">
                  <option value="">请选择授权类型</option>
                  <option value="长期">长期</option>
                  <option value="短期">短期</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权日期</label>
                <input type="datetime-local" v-model="newVehicle.reviewTime" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">结束日期</label>
                <input type="datetime-local" v-model="newVehicle.endTime" class="input" />
              </div>
            </div>

            <div class="mt-4 flex justify-end">
              <button @click="submitNewVehicle" class="btn btn-primary mr-2">
                确定
              </button>
              <button @click="closeAddDialog" class="btn btn-outline">
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport> -->

  <!-- 修改车辆编辑对话框 -->
  <!-- <Teleport to="body">
    <Transition name="fade" appear>
      <div v-if="isEditDialogOpen && activeTab === 'vehicle'">
        <div class="bg-background/80 fixed inset-0 z-50 flex items-center justify-center backdrop-blur-sm">
          <div class="bg-card text-card-foreground w-[800px] rounded-lg p-5 shadow-xl">
            <div class="mb-4 flex items-center justify-between">
              <h3 class="text-lg font-bold">编辑车辆</h3>
              <button @click="closeEditDialog" class="text-muted-foreground hover:text-foreground">
                <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>


            <div class="grid grid-cols-3 gap-4">

              <div>
                <label class="block text-sm font-medium">车牌号</label>
                <input type="text" v-model="editingRecord.plateNumber" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">驾驶员姓名</label>
                <input type="text" v-model="editingRecord.driverName" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">车辆类型</label>

                <select v-model="editingRecord.vehicleType" class="select">
                  <option value="">请选择授权区域</option>
                  <option value="普货车">普货车</option>
                  <option value="社会车辆">社会车辆</option>
                  <option value="其他">其他</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权区域</label>
                <select v-model="editingRecord.passArea" class="select">
                  <option value="">请选择授权区域</option>
                  <option value="综合服务区">综合服务区</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权类型</label>
                <select v-model="editingRecord.authorizationType" class="select">
                  <option value="">请选择授权类型</option>
                  <option value="长期">长期</option>
                  <option value="短期">短期</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium">授权日期</label>
                <input type="datetime-local" v-model="editingRecord.reviewTime" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium">结束日期</label>
                <input type="datetime-local" v-model="editingRecord.endTime" class="input" />
              </div>
            </div>
            <div class="mt-4 flex justify-end">
              <button @click="submitEditVehicle" class="btn btn-primary mr-2">
                确定
              </button>
              <button @click="closeEditDialog" class="btn btn-outline">
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport> -->
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { dayjs } from 'element-plus'
import axios from 'axios'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()

const apiBaseUrl = ref(proxy.$currentUrl + '/api')

const formItems = ref([
  {
    label: '人员编码：',
    model: 'STAFF_CODE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '人员姓名：',
    model: 'STAFF_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '人员类型：',
    model: 'STAFF_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '企业内部人员', value: '企业内部人员' },
      { label: '园区工作人员', value: '园区工作人员' },
      { label: '承包商人员', value: '承包商人员' },
      { label: '临时访客', value: '临时访客' },
      { label: '应急教授人员', value: '应急教授人员' },
      { label: '上级部门检查人员', value: '上级部门检查人员' },
      { label: '驾驶员', value: '驾驶员' },
      { label: '押运员', value: '押运员' },
      { label: '其他', value: '其他' },
    ],
  },
  {
    label: '授权类型：',
    model: 'AUTHORIZATION_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '长期', value: '长期' },
      { label: '临时', value: '临时' },
    ],
  },
])
const vehicleformItems = ref([
  {
    label: '车牌号码：',
    model: 'PLATE_NUMBER',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '驾驶员姓名：',
    model: 'DRIVER_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '授权类型：',
    model: 'STATUS',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '长期', value: '长期' },
      { label: '临时', value: '临时' },
    ],
  },
])
const activeTab = ref('personnel')


const selectAllPersonnel = ref(false)
const selectAllVehicle = ref(false)
const displayedVehicleData = ref([])
const currentPageCar = ref(1)
const displayedVehicleDataCar = ref([])
const alltabledata = (data) => {
  displayedVehicleDataCar.value = data

}
const alltabledatass = (data) => {
  displayedVehicleData.value = data

}

// const displayedVehicleDataCar = computed(() => {
//   const start = (currentPageCar.value - 1) * pageSizeCar.value
//   const end = start + pageSizeCar.value
//   return vehicleData.value.slice(start, end)
// })

const personnelSearch = ref({
  STAFF_CODE: '',
  STAFF_NAME: '',
  STAFF_TYPE: '',
  AUTHORIZATION_TYPE: '',
})

const vehicleSearch = ref({
  PLATE_NUMBER: '',
  DRIVER_NAME: '',
  STATUS: '',
})

const personnelData = ref([

])
const selectAll = ref(false)
const vehicleData = ref([

  // 添加更多车辆数据...
])

// 对话框状态
const isAddDialogOpen = ref(false)
const isEditDialogOpen = ref(false)
const editingRecord = ref({
  STAFF_CODE: '',
  STAFF_NAME: '',
  STAFF_TYPE: '',
  STAFF_GENDER: '',
  AFFILIATION: '',
  STAFF_POSITION: '',
  AUTHORIZATION_TYPE: '',
  REVIEW_TIME: '',
  END_TIME: '',
})
const currentPage = ref(1)





const resetPersonnelSearch = () => {
  // Object.keys(personnelSearch.value).forEach((key) => (personnelSearch.value[key] = ''))
  // allPersonnel()
  personnelSearch.value = {
    STAFF_CODE: '',
    STAFF_NAME: '',
    STAFF_TYPE: '',
    AUTHORIZATION_TYPE: '',
  }
  searchdata()
}

const addPersonnel = () => {
  isDialogType.value = 'add'
  isAddDialogOpen.value = true
}

const deletePersonnel = async (row) => {
  try {
    if (confirm('是否解除')) {
      axios.delete(`${apiBaseUrl.value}/personnel-autopass-record/${row.ID}`)
      alert('解除成功')
      await searchdata()
      selectAllVehicle.value = false
    }
  } catch (error) {
    console.error('解除记录失败:', error)
    alert('解除记录失败: ' + (error.response?.data?.message || error.message))
  }
}

const importPersonnel = () => {
  // 创建一个隐藏的文输入元素
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = '.xlsx, .xls, .csv'
  fileInput.style.display = 'none'

  fileInput.onchange = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    const formData = new FormData()
    formData.append('file', file)

    try {
      const response = await axios.post('/api/personnel/import', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
      alert(response.data.message || '导入成功')
      searchdata()
    } catch (error) {
      console.error('导入失败:', error)
      alert('导入失败: ' + (error.response?.data?.message || error.message))
    } finally {
      document.body.removeChild(fileInput)
    }
  }

  document.body.appendChild(fileInput)
  fileInput.click()
}

const exportPersonnel = () => {
  const wb = XLSX.utils.book_new()
  const exportData = personnelData.value.map((record) => ({
    人员编码: record.STAFF_CODE,
    人员姓名: record.STAFF_NAME,
    人员类型: record.STAFF_TYPE,
    所属单位: record.AFFILIATION,
    职位名称: record.STAFF_POSITION,
    授权类型: record.AUTHORIZATION_TYPE,
    授权日期: formatDateTime(record.REVIEW_TIME),
    到期日期: formatDateTime(record.END_TIME),
  }))

  const ws = XLSX.utils.json_to_sheet(exportData)
  XLSX.utils.book_append_sheet(wb, ws, '人员自动放行')

  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '人员自动放行.xlsx'
  link.click()
  URL.revokeObjectURL(link.href)
}

// 辅助函数
function s2ab(s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
  return buf
}


const updateSelectAllState = () => {
  if (activeTab.value == 'personnel') {
    selectAllPersonnel.value = personnelData.value.length > 0 && personnelData.value.every(app => app.selected)
  } else {
    selectAllVehicle.value = selectAllVehicle.value.length > 0 && selectAllVehicle.value.every(app => app.selected)
  }
}
const editPerson = (person) => {
  editingRecord.value = { ...person }
  editingRecord.value.REVIEW_TIME = formatDateTimeForAPI(person.REVIEW_TIME)
  editingRecord.value.END_TIME = formatDateTimeForAPI(person.END_TIME)


  isEditDialogOpen.value = true
}

const resetVehicleSearch = () => {
  vehicleSearch.value = {
    PLATE_NUMBER: '',
    DRIVER_NAME: '',
    AUTHORIZATION_TYPE: '',
  }
  searchdataCar()
}


const deleteVehicle = async (row) => {
  try {
    if (confirm('是否解除')) {
      await axios.delete(`${apiBaseUrl.value}/vehicle-autopass-record/${row.ID}`)
      alert('解除成功')
      await searchdataCar()
      selectAll.value = false
    }
  } catch (error) {
    console.error('解除记录失败:', error)
    alert('解除记录失败: ' + (error.response?.data?.message || error.message))
  }
}

const importVehicle = () => {
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = '.xlsx, .xls, .csv'
  fileInput.style.display = 'none'

  fileInput.onchange = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    const formData = new FormData()
    formData.append('file', file)

    try {
      const response = await axios.post('/api/vehicles/import', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
      alert(response.data.message || '导入成功')
      searchVehicle()
    } catch (error) {
      console.error('导入失败:', error)
      alert('导入失败: ' + (error.response?.data?.message || error.message))
    } finally {
      document.body.removeChild(fileInput)
    }
  }

  document.body.appendChild(fileInput)
  fileInput.click()
}

const exportVehicle = () => {
  const wb = XLSX.utils.book_new()

  const exportData = vehicleData.value.map((record) => ({
    车牌号: record.PLATE_NUMBER,
    驾驶员姓名: record.DRIVER_NAME,
    车辆类型: record.VEHICLE_TYPE,
    授权区域: record.CarArray,
    授权类型: record.STATUS,
    授权日期: formatDateTime(record.Authorization_Date),
    到期日期: formatDateTime(record.EXPIRATION_DATE),
  }))

  const ws = XLSX.utils.json_to_sheet(exportData)
  XLSX.utils.book_append_sheet(wb, ws, '车辆自动放行')

  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '车辆自动放行.xlsx'
  link.click()
  URL.revokeObjectURL(link.href)
}








const editVehicle = (vehicle) => {
  editingRecord.value = { ...vehicle }
  editingRecord.value.Authorization_Date = formatDateTimeForAPI(vehicle.Authorization_Date)
  editingRecord.value.EXPIRATION_DATE = formatDateTimeForAPI(vehicle.EXPIRATION_DATE)
  isEditDialogOpen.value = true
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
}

const closeEditDialog = () => {
  isEditDialogOpen.value = false
  editingRecord.value = {}
}

// 添加新的响应式变量
const newPersonnel = ref({
  reviewTime: "",
  endTime: "",
  staffCode: "",
  staffName: "",
  staffType: "",
  affiliation: "",
  sexual: "",
  authorizationType: "",
  staffPosition: ""
})

// 添加提交方法
const submitNewPersonnel = async () => {
  try {
    // 这里添加实际的API调用
    console.log('Submitting new personnel:', newPersonnel.value)
    newPersonnel.value.reviewTime = formatDateTimeForAPI(newPersonnel.value.reviewTime)
    newPersonnel.value.endTime = formatDateTimeForAPI(newPersonnel.value.endTime)
    const response = await axios.post(`${apiBaseUrl.value}/personnel-autopass-record`, {
      ...newPersonnel.value,
    })
    alert(response.data.message || '添加成功')
    closeAddDialog()
    await searchdata()
  } catch (error) {
    console.error('添加失败:', error)
    alert('添加失败: ' + (error.response?.data?.message || error.message))
  }
}

const submitEditPersonnel = async () => {
  try {

    if (activeName.value == '人员') {

      // 这里添加实际的API调用
      console.log('Submitting edit personnel:', editingRecord.value)
      const response = await axios.put(`${apiBaseUrl.value}/personnel-autopass-record/${editingRecord.value
        .ID}`, editingRecord.value)
      alert(response.data.message || '更新成功')
      closeEditDialog()
      await searchdata()
    } else {
      console.log('Submitting edit vehicle:', editingRecord.value)
      const response = await axios.put(`${apiBaseUrl.value}/vehicle-autopass-record/${editingRecord.value
        .ID}`, editingRecord.value)
      alert(response.data.message || '更新成功')
      closeEditDialog()
      await searchdataCar()
    }
  } catch (error) {
    console.error('更新失败:', error)
    alert('更新失败: ' + (error.response?.data?.message || error.message))
  }
}

// 添加新的响应式变量
const newVehicle = ref({
  plateNumber: '',
  driverName: '',
  vehicleType: '',
  passArea: '',
  authorizationType: '',
  reviewTime: '',
  endTime: '',
})

// 修改车辆相关的方法
const submitNewVehicle = async () => {
  try {
    // 这里添加实际的API调用
    console.log('Submitting new vehicle:', newVehicle.value)
    newVehicle.value.reviewTime = formatDateTimeForAPI(newVehicle.value.reviewTime)
    newVehicle.value.endTime = formatDateTimeForAPI(newVehicle.value.endTime)
    const response = await axios.post(`${apiBaseUrl.value}/vehicle-autopass-record`, {
      ...newVehicle.value,
    })
    alert(response.data.message || '添加成功')
    closeAddDialog()
    await allVehicle()
  } catch (error) {
    console.error('添加失败:', error)
    alert('添加失败: ' + (error.response?.data?.message || error.message))
  }
}

const submitEditVehicle = async () => {
  try {
    // 这里添加实际的API调用
    console.log('Submitting edit vehicle:', editingRecord.value)
    const response = await axios.put(`${apiBaseUrl.value}/vehicle-autopass-record/${editingRecord.value
      .ID}`, editingRecord.value)
    alert(response.data.message || '更新成功')
    closeEditDialog()
    await allVehicle()
  } catch (error) {
    console.error('更新失败:', error)
    alert('更新失败: ' + (error.response?.data?.message || error.message))
  }
}

///////////////////

const formatDateTimeForAPI = (dateTimeString) => {
  if (!dateTimeString) return null
  const date = dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
  return date
}









//////////
const btntab = (data) => {
  updateSelectAllState()
  activeTab.value = data
  searchdata()
  selectedIds.value = []
}
const activeName = ref('人员')
const handleClick = (tab, event) => {
  if (tab == '人员') {
    searchdata()
  } else if (tab == '车辆') {
    searchdataCar()
  }
}



const tableRef = ref(null)

// 查询
const searchdata = async () => {
  displayedVehicleData.value = []
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/personnel-autopass-record/search`, {
      params: personnelSearch.value,
    })
    currentPage.value = 1
    personnelData.value = response.data
    loading.value = false
  } catch (error) {
    console.error('获取所有记录失败:', error)
    alert(
      '获取所有记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const searchdataCar = async () => {
  displayedVehicleDataCar.value = []
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/vehicle-autopass-record/search`, {
      params: vehicleSearch.value,
    })
    vehicleData.value = response.data.map((alarm) => ({
      ...alarm,
      selected: false,
    }))
    currentPageCar.value = 1
    loading.value = false
  } catch (error) {
    console.error('获取所有记录失败:', error)
    alert(
      '获取所有记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const rowKey = (row) => row.ID
// 添加格式化日期时间的辅助函数
const formatDateTimeForInput = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toISOString().slice(0, 16) // 格式为 "YYYY-MM-DDTHH:mm"
}
// 表头样式
const headerCellStyle = {
  height: '45px', // 设置表头高度
  lineHeight: '50px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const rules = {
  STAFF_CODE: [
    { required: true, message: '请输入人员编码', trigger: 'blur' },
  ],
  STAFF_NAME: [
    { required: true, message: '请输入人员姓名', trigger: 'blur' },
  ],
  STAFF_TYPE: [
    { required: true, message: '请选择人员类型', trigger: 'change' },
  ],
  STAFF_GENDER: [
    { required: true, message: '请选择性别', trigger: 'change' },
  ],
  AFFILIATION: [
    { required: true, message: '请选择所属单位', trigger: 'change' },
  ],
  STAFF_POSITION: [
    { required: true, message: '请选择职位名称', trigger: 'change' },
  ],
  AUTHORIZATION_TYPE: [
    { required: true, message: '请选择授权类型', trigger: 'change' },
  ],
  REVIEW_TIME: [
    { required: true, message: '请选择授权日期', trigger: 'change' },
  ],
  END_TIME: [
    { required: true, message: '请选择到期日期', trigger: 'change' },
  ],
}
const formRef = ref(null)
const isDialogType = ref('')
const loading = ref(false)
const selectedIds = ref([])

// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}
// ... 其他函数保持不变
onMounted(() => {
  searchdata()
})
</script>

<style scoped>
.input,
.select {
  @apply border-input bg-background focus:border-primary focus:ring-primary mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:ring focus:ring-opacity-50;
}

.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-outline {
  @apply border-input bg-background hover:bg-muted hover:text-muted-foreground border;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

/* 添加过渡动画样式 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}
</style>
